package com.rr.learningdemo.rabbitmq.thread;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Set;

/**
 * @author zhuangcanrun
 * @Date 2021/06/21/17:47
 * @description
 **/

@Component
public class RedisListenerThread extends Thread {

    @Autowired
    private RedisTemplate redisTemplate;

    private final Object lock = new Object();

    /*
    调用该方法实现恢复线程的运行
     */
    public void resumeThread(){
        System.out.println("继续监听redis的set");
        synchronized (lock){
            lock.notify();
        }
    }

    private void onPause() {
        synchronized (lock) {
            try {
                System.out.println("停止监听redis的set");
                lock.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void run() {
        System.out.println("监听redis的set");

        while (true) {
            Set list = redisTemplate.opsForSet().members("set");
            if (list == null || list.isEmpty()) {
                onPause();
                continue;
            }
            for (Object o : list) {
                redisTemplate.opsForSet().remove("set", o);
                System.out.println("消费:" + o);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
